<?php
class DXBase
{
	private static $_aliases=array('system'=>DX_PATH); // alias => path
	private static $_imports=array();					// alias => class name or directory
	private static $_classes=array();
	private static $_app;
	
	public static function createWebApp(){
		return new DWebApplication();
	}
	
	public static function app(){
		return self::$_app;
	}
	
	public static function setApplication($app){
		if(self::$_app===null || $app===null)
			self::$_app=$app;
		else
			throw new DException('Yii application can only be created once');
	}
	
	public static function getPathOfAlias($alias){
		if(isset(self::$_aliases[$alias]))
			return self::$_aliases[$alias];
		else if(($pos=strpos($alias,'.'))!==false){
			$rootAlias=substr($alias,0,$pos);
			if(isset(self::$_aliases[$rootAlias]))
				return self::$_aliases[$alias]=rtrim(self::$_aliases[$rootAlias].DIRECTORY_SEPARATOR.str_replace('.',DIRECTORY_SEPARATOR,substr($alias,$pos+1)),'*'.DIRECTORY_SEPARATOR);
			else if(self::$_app instanceof DWebApplication){
				if(self::$_app->findModule($rootAlias)!==null)
					return self::getPathOfAlias($alias);
			}
		}
		return false;
	}
	
	public static function setPathOfAlias($alias,$path)
	{
		if(empty($path))
			unset(self::$_aliases[$alias]);
		else
			self::$_aliases[$alias]=rtrim($path,'\\/');
	}
	
	public static function autoload($className){
		if(isset(self::$_coreClasses[$className]))
			include(DX_PATH.self::$_coreClasses[$className]);
		else if(isset(self::$_classes[$className])){
			include(self::$_classes[$className]);
		}else{
			include($className.'.class.php');
			return class_exists($className,false) || interface_exists($className,false);
		}
		return true;
	}
	
	private static $_coreClasses=array(
		'DComponent'      => '/lib/core/DComponent.class.php',
		'DModule'         => '/lib/core/DModule.class.php',
		'DApplication'    => '/lib/core/DApplication.class.php',
		'DWebApplication' => '/lib/core/DWebApplication.class.php',
		'DBaseControl'    => '/lib/core/DBaseControl.class.php',
		'DControl'        => '/lib/core/DControl.class.php',
		'DHttpRequest'    => '/lib/core/DHttpRequest.class.php',
		'DModel'          => '/lib/core/DModel.class.php',
		'DActiveRecord'   => '/lib/core/DActiveRecord.class.php',
		'DRoute'          => '/lib/core/DRoute.class.php',
		'DAction'         => '/lib/core/DAction.class.php',
		'DRunAction'      => '/lib/core/DRunAction.class.php',
		'DDbconnect'      => '/lib/db/DDbconnect.class.php',
		'DCache'          => '/lib/cache/DCache.class.php',
	);
}
spl_autoload_register(array('DXBase','autoload'));
?>